package com.pzh.vue.config.Interceptor;

import cn.hutool.jwt.JWTException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.pzh.vue.common.Constants;
import com.pzh.vue.config.InterceptorConfig;
import com.pzh.vue.exception.ServiceException;
import com.pzh.vue.pojo.SysUser;
import com.pzh.vue.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class JWTInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(JWTInterceptor.class);
    @Autowired
    SysUserService sysUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("current request url={}",request.getRequestURI());
        String token = request.getHeader("token");
        //如果不是映射方法直接通过
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        //执行认证
        if (StringUtils.isEmpty(token)){
            throw new ServiceException(Constants.CODE_401,"无token，请登录");
        }
        String userId;
        try{
             userId= JWT.decode(token).getAudience().get(0);//获取token中的userId
        }catch (JWTException e){
            throw new ServiceException(Constants.CODE_401,"token验证失败,error");
        }
        //根据token得到的id查询
        SysUser user = sysUserService.getById(userId);
        if (user==null){
            throw new ServiceException(Constants.CODE_401,"用户不存在，重新登录");
        }
        //用户密码验证token
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try{
            jwtVerifier.verify(token);
        }
        catch (JWTVerificationException e){
            throw new ServiceException(Constants.CODE_401,"token验证失败,请重新登录");
        }
        return true;
    }
}
